package com.platform.qujia.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

/**
 * @date 2024/2/4
 */
@Component
public class FreeMarkerUtil {

    @Autowired
    @Qualifier("freeMarkerConfiguration")
    private Configuration freeMarkerConfiguration;

    public Template getTemplate(String name) throws IOException {
        return freeMarkerConfiguration.getTemplate(name);
    }

    public void process(String templateName, Map<String,Object> context, Writer writer) throws TemplateException, IOException {
        Template template = getTemplate(templateName);
        template.process(context,writer);
    }

    public String process(String templateName,Map<String,Object> context) throws TemplateException, IOException {
        StringWriter stringWriter = new StringWriter();
        process(templateName,context,stringWriter);
        return stringWriter.toString();
    }

}
